import { Component, OnInit, DoCheck } from '@angular/core';
import { UserServiceService } from "../user-service.service";
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { User } from "../User";
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { UntypedFormBuilder, UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { FormGroup, FormBuilder } from '@angular/forms';
@Component({
    selector: 'app-user-form',
    templateUrl: './user-form.component.html',
    styleUrls: ['./user-form.component.less']
})
export class UserFormComponent implements OnInit, DoCheck {
    fromModel!: UntypedFormGroup
    /**
     * 初始化user集合
     */
    users: User[] = []
    /**
     * 初始化实例
     */
    user: User = {
        id: '',
        sex: '',
        name: "",
        addr: ''
    }


    onSubmit(): void {
       
        console.log("进行了提交")
    }

    id: number = Number(this.route.snapshot.paramMap.get('id'))
    userId: number = 0;
    buttonValue: string = "新增"
    divtitle: string = "学生情报追加"
    Disflag: boolean = true
    isVisible = false;
    isOkLoading = false;
    register: boolean = false;
    dis = false;


    /**
     * 私有化处理
     * @param route
     * @param userService
     * @param location
     */
    constructor(private route: ActivatedRoute,
        private userService: UserServiceService,
        private location: Location,
        private modalService: NzModalService,
        private fb: UntypedFormBuilder) {

    }

    /**
     * 在Angular第一次显示数据绑定和设置组件/指令的输入属性后
     * 初始化组件或指令。在第一轮ngOnChanges()完成之后调用，只调用一次
     * 使用该构造函数有两个原因。其一在构造函数之后马上执行复杂的初始化逻辑。其二在 Angular 设置完输入属性之后，对该组件进行准备。
     * 
     * ngOnInit主要用来做请求数据
     */
    ngOnInit(): void {

        if (this.id > 0) {
            this.getUserById()
            this.fromModel = this.fb.group({
                id: [{ value: null, disabled: true },[Validators.required]],
                name: [{ value: null, disabled: true }, [Validators.required]],
                sex: [null],
                addr: [null],

            })
        }
        else {
            this.fromModel = this.fb.group({
                id: [null,[Validators.required]],
                sex: [null, [Validators.required]],
                name: [null],
                addr: [null],

            })
        }
    }


    /**
       * 该函数在ngOnInt函数之后触发。ngDoCheck()中可以做一些自定义的操作，比如查看数据是否改变
       */
    ngDoCheck(): void {
        //写一些自定义操作
        this.changeButton()
    }

    flag: boolean = false

    /**
     * 判空
     * @constructor
     */
    NotNull() {
        return this.user.name == null || this.user.name == undefined || this.user.name == ''
    }
    /**
     * 修改sex值
     * @param user 
     */
    changeSex(user: User) {
        if (user.sex == "1") {
            user.sex = "男"
        }
        else if (user.sex == "0") {
            user.sex = "女"
        }
        else if (user.sex == "男") {
            user.sex = "1"
        } else if (user.sex == "女") {
            user.sex = "0"
        }


    }
    /**
      * 弹出对话框
      */
    showModal(): void {
        this.isVisible = true;
    }
    /**
     * 点击对话框里的ok
     */
    handleOk(): void {
        this.isVisible = false;
        this.register = true
    }
    /**
     * 点击对话框里的no
     */
    handleCancel(): void {
        this.isVisible = false;
        this.goBack()

    }

    /**
     * 返回上一级路由
     */
    goBack(): void {
        this.location.back();
    }

    /**
     * 改变按钮value属性
     */
    changeButton() {

        if (!(this.fromModel.value.name && this.user.id)) {
            this.Disflag = true
        }
        if (this.fromModel.value.name && this.fromModel.value.id) {
            this.Disflag = false

        }


    }


    /**
     * 新增用户的服务
     * @param user
     */
    add(user: User) {
        this.userService.addUser(user)
            .subscribe(() => {
                this.users.push(user)
                this.goBack()
            });
    }

    /**
     * 更新用户信息的服务
     * @param user
     */
    update(user: User) {
        this.userService.updateHero(user)
            .subscribe((any) => this.goBack());
    }

    /**
     * 从路由获取用户信息
     * 另外赋值用户id
     */
    getUserById(): void {
        this.userService.getUser(this.id)
            .subscribe((res) => {
                this.changeSex(res.data.message)
                this.user = res.data.message
                this.fromModel.patchValue(this.user);
                this.userId = Number(res.data.message.id)
                this.divtitle = "学生情报变更"
                this.dis = true;
                console.log(this.dis)

            })
    }

    /**
     * 对比一遍已存在的用户
     */
    getUsername() {
        this.userService.getUsers()
            .subscribe((res) => {
                this.users = res.data.list
                for (let i = 0, length = this.users.length; i < length; i++) {
                    if (this.user.id == this.users[i].id) {
                        window.alert("No不可重复")
                        this.flag = false
                    } else this.flag = true
                }
            })
    }

    showConfirm(): void {
        this.modalService.confirm({
            nzTitle: '<i>確認メッセージ</i>',
            nzOnOk: () => this.handleOk(),
            nzOnCancel: () => this.handleCancel()
        });
    }

    /**
        * 新增用户的方法
        * @param user
        */
    addUser(user: User) {
        this.getUsername()
        setTimeout(() => {//堵塞flag
            if (this.flag) {
                this.showModal() //调出对话框
                let timer = setInterval(() => {//调整速率
                    if (this.register) {
                        if (this.register) {
                            this.changeSex(user)
                            user = this.fromModel.value
                            this.add(user)
                        }
                        else { this.goBack() }
                        clearInterval(timer)
                    }
                }, 1);

            }
        }, 500);

    }

    /**
    * 更新用户的方法
    * @param user
    */
    updateUser(user: User) {
        if (this.NotNull()) {
            window.alert("姓名不可为空")
        } else {

            this.showModal() //调出对话框
            let timer = setInterval(() => {//调整速率
                if (this.register) {
                    if (this.register) {
                        this.changeSex(user)
                        user = this.fromModel.value
                        this.update(user)
                    }
                    else { this.goBack() }
                    clearInterval(timer)
                }
            }, 1);

        }

    }
}






